import {
    Injectable,
    NestInterceptor,
    ExecutionContext,
    CallHandler,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { SKIP_RESPONSE_INTERCEPTOR_KEY } from './skip-response-interceptor.decorator';

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
    constructor(private reflector: Reflector) {}

    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const handler = context.getHandler();
        const skip = this.reflector.getAllAndOverride<boolean>(SKIP_RESPONSE_INTERCEPTOR_KEY, [
          context.getClass(),
          handler,
        ]);
    
        if (skip) {
          return next.handle();
        }
    
        return next.handle().pipe(
          map(result => ({
            type: 'success',
            result,
            code: 200,
            message: '请求成功',
            timestamp: new Date().toISOString(),
          })),
        );
      }
    // intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    //     return next.handle().pipe(
    //         map(result => ({
    //             type: 'success',
    //             result,
    //             code: 200,
    //             message: '请求成功',
    //             timestamp: new Date().toISOString(),
    //         })),
    //     );
    // }
}
